<template>
  <!--
    1、自定义图片展示
      要求：1、支持多图片展示，图片最大展示多少张，当超过宽度，用滚动条
      2、每个图片都有一个删除标识
      3、上传按钮

      传入组件
      1、图片集合 imgList [图片地址1,图片地址2, ......]，当imgs 发生改变的时候对应的调用的也能获取到
      2、上传按钮的文字、颜色类型 有默认‘上传图片’，‘主要’

      setDirection 后续修改
   -->

  <div class="img-main" :style="setDirection" ref="container" :key="customImgMainId">

    <!--图片区域-->
    <div class="img-item-div" :key="item+index" v-for="(item,index) in imgList">
      <div class="img-item-box" @mouseenter="mouseenterImg(item,index)"
           @mouseleave="mouseleaveImg(item,index)">
        <!--删除文字-->
        <div class="span-item-box" :id="'span-item-'+index"
             @mouseenter="mouseenterImg(item,index)" @mouseleave="mouseleaveImg(item,index)"
        >
          <span class="span-item" @click="itemImgClick(item,index)">删除</span>
        </div>
        <!--展示图片-->
        <div class="img-item">
          <el-image @mouseenter="mouseenterImg(item,index)" @mouseleave="mouseleaveImg(item,index)"
                    :src="'/api/source/'+item">
          </el-image>
        </div>
      </div>
    </div>
  </div>
  <input class="input-file-item" v-show="false" @change="upload($event)" id="inputFileItemId" type="file" multiple/>
  <el-button type="primary" @click="uploadImg()">文件上传</el-button>
</template>

<script>
import {upload} from "@/components/request/publicApi";

export default {
  name: "customImg",
  props: {
    /*下标*/
    index: {type: Number},
    /*传入的元素*/
    colItem: {type: Object},
    customImgList: {
      type: Array,
      default: () => {
        return []
      }
    },
    /*盒子的方向 横向row 纵向 column*/
    flexDirection: {
      type: String,
      default: () => {
        return "column"
      }
    },
    /*上层div 的宽度*/
    superDivWidth: {
      type: Number,

    }

  },
  data() {
    return {
      images: [],
      totalWidth: 0,
      customImgMainId: "customImgMainId",
      imgList: this.customImgList
    }
  },
  emits: ['synElementImgData'],
  /*监听*/
  watch: {
    // imgList(newName, oldName) {
    //   console.log('监听imgList(newName, oldName)')
    //   console.log( newName + ' ' + oldName);
    // },
    //imgList
    'imgList': {
      handler(newName, oldName) {
        // console.log('监听imgList(newName, oldName)')
        // console.log(newName + ' ' + oldName);

      },
      deep: true,
      immediate: true
    },
    customImgList(newValue) {
      // console.log('监听customImgList(newName, oldName)')
      this.imgList = newValue; // 在customImgList变化时更新imgList
    }
  },
  /*计算属性*/
  computed: {
    /*动态的方向由父组件传入*/
    setDirection() {
      return {'flex-direction': this.flexDirection};
    }

  },
  methods: {
    /*图片上传的触发方法*/
    uploadImg() {
      // console.log('aaa')
      // document.getElementById("inputFileItem")
      //     .click()
      let inputFileItem = document.getElementById("inputFileItemId");
      inputFileItem.click();
      // return;
    },
    /*文件上传*/
    upload(event, colItem) {
      // console.log('文件上传信息', event, colItem)
      let data = {'file': event.target.files[0]}
      let that = this;
      upload(data).then((res) => {
        // colItem.itemValue = res.data.data.path;
        // that.imgList=[...that.imgList,res.data.data.path]
        that.imgList.push(res.data.data.path)
        that.customImgMainId = Math.random().toString(36);
        // console.log('文件返回信息res', res)
        // console.log('文件返回信息imgList', that.imgList)
        this.synElement()
      }).catch(error => {
        // console.log(error)
      })

    },
    /*图片点击删除数据*/
    itemImgClick(item, index) {
      // console.log('itemImgClick', item);
      // console.log('itemImgClick', index);
      // .splice(index, 1);
      // this.customImgList.splice(index, 1);
      this.imgList.splice(index, 1);
      this.customImgMainId = Math.random().toString(36);

      this.synElement()
    },
    synElement() {
      let element = this.imgList.toString()
      // console.log('synElement',element)
      this.$emit('synElementImgData', element, this.colItem, this.index)
    },
    /*鼠标移入图片的时间*/
    mouseenterImg(item, index) {
      // console.log('onmouseenterImgitem', item);
      // console.log('onmouseenterImgindex', index);
      let element = document.getElementById('span-item-' + index);
      element.style.visibility = 'visible';

    },
    /*鼠标移出图片的时间*/
    mouseleaveImg(item, index) {
      // console.log('onmouseleaveImgitem', item);
      // console.log('onmouseleaveImgindex', index);
      let element = document.getElementById('span-item-' + index);
      element.style.visibility = 'hidden';
    },
    handleFileUpload(event) {
      const files = event.target.files;
      if (!files || files.length === 0) return;

      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const reader = new FileReader();
        reader.onload = () => {
          const img = new Image();
          img.src = reader.result;
          img.onload = () => {
            const newImage = {
              url: reader.result,
              width: img.width
            };
            this.images.push(newImage);
            this.calculateTotalWidth();
          };
        };
        reader.readAsDataURL(file);
      }
    },
    calculateTotalWidth() {
      // Get container width
      const containerWidth = this.$refs.container.offsetWidth;
      // console.log('containerWidth', containerWidth)
      // Calculate total width of images
      let totalWidth = 0;
      this.images.forEach(image => {
        totalWidth += image.width;
      });

      if (totalWidth > containerWidth) {
        // Set totalWidth to trigger scrollbar
        this.totalWidth = totalWidth;
      } else {
        this.totalWidth = containerWidth;
      }
    }
  },
  mounted() {
    // console.log('mounted',this.customImgList)
  },
  created() {
    // console.log('created', this.customImgList)
    this.imgList = this.customImgList
  },
  beforeCreate() {
    // console.log('beforeCreate', this.customImgList)
    this.imgList = this.customImgList
  }
}
</script>

<style scoped lang="less">

.img-main {
  width: 280px;
  //border: 1px solid red;
  overflow-x: auto;
  //overflow-y: auto;
  white-space: nowrap;

  .img-item-div {
    display: inline-block;
    //border: 1px solid red;
    .img-item-box {
      padding: 5px;
      width: 100px;
      //border: 1px solid red;
      .img-item {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }

    }

    .span-item-box {
      /*尾部开始*/
      direction: rtl;
      text-align: right;
      visibility: hidden;
      //visibility: visible;
      .span-item {
        position: relative;
        top: 15px;
        z-index: 100;
        color: red;
      }

    }
  }

  .input-file-item {
    display: none;
    border: 1px solid red;
  }
}

//.img-main {
//  display: flex;
//  //justify-content: center;
//  //align-items: center;
//  width: 280px;
//  height: 130px;
//  overflow-x: auto;
//  white-space: nowrap;
//
//  .img-item-div {
//    width: 120px;
//    height: 100px;
//
//    .img-item-div-one {
//      display: inline-block;
//      padding: 5px;
//
//      .img-item {
//        width: 100%;
//        height: 100%;
//        margin-left: 10px;
//        //background-size: contain
//        object-fit: contain;
//      }
//
//      .item-Img-Del-Box {
//        cursor: pointer;
//        position: relative;
//        /* 距离顶部的距离 */
//        top: -90px;
//        /* 距离右侧的距离 */
//        right: -90px;
//        //display: none;
//        //background-color: green;
//        color: red;
//        z-index: 100;
//      }
//    }
//
//  }
//}
</style>


